<?php
/**
 * 图片
 * ***********************
 * * Author:蜗牛他大哥    *
 * * Time: 2018-05-23    *
 * * QQ交流群：101766150  *
 * ***********************
 * */
namespace app\img\controller;

class Img extends ImgBase
{
    protected $model;
    protected $folderModel;
    protected $imSiteModel;
    protected $pagesize = 30;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = Model('common/img');
        $this->folderModel = Model('common/imgFolder');
        $this->imgSiteModel = Model('common/imgSite');
    }

    public function index()
    {
        $folder = $this->folderModel->folderPidData();

        //unlink(UPLOADS_IMAGES.'/20180417_efb160880045210a2447f6f4d67785d1.jpg');
        //echo config('view_replace_str.__UPLOADS__');


        $imgsite = session('imgSite');
        $res['siteOpt'] = $this->imgSiteModel->opt($imgsite);
        $res['folder'] = $folder;
        $this->assign('res',$res);
        return $this->fetch();
    }

    /**
     * 上传
     * */
    public function upload(){
        $pid = intval(input('pid'))?intval(input('pid')):0;
        $res['pid'] = $pid;
        $res['title'] = '上传';
        $res['base_php'] = url('img/uploader',array('pid'=>$pid));
        $this->assign('res',$res);
        return $this->fetch();
    }
    /**
     * 插入数据
     * 百度Web Uploader 插件
     * php服务器
     * */
    public function uploader(){
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        $pid = intval(input('pid'));

        // Support CORS
        // header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }


        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        usleep(5000);

        // Settings
        // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        //$targetDir = 'upload_tmp';
        //$uploadDir = 'uploads/images/';
        //$uploadDir = config('view_replace_str.__UPLOADS__');
        // 获取img_site 的folder字段（站点文件夹）
        $site = $this->imgSiteModel->comGet(session('imgSite'));

        // 上传路径
        $uploadDir = UPLOADS_IMAGES.$site['folder'];
        $targetDir = $uploadDir.'/upload_tmp';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds


        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

        $md5File = @file('md5list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $md5File = $md5File ? $md5File : array();

        if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File ) !== FALSE ) {
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1}');
        }

        /**
         * 图片重新重命名
         * time: 2018-04-04
         * */

        $suffix = explode('.',$fileName);   // 获取文件后缀
        $oldName =  reset($suffix);
        $fileName = $this->model->imgName().'.'.end($suffix);
        //file_put_contents('1.txt',$this->ImgName());

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;


        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {

                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }



        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);

                        /*图片入库*/
                        $data['pid'] = $pid?$pid:0;
                        $data['name']  = $oldName;
                        $data['path'] = $site['folder'].'/'.$fileName;
                        $data['site'] = session('imgSite');
                        $data['add_time'] = time();
                        $this->model->comSave($data);
                        /*图片入库 End*/
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);

            array_push($md5File, md5(file_get_contents($uploadPath)));
            $md5File = array_unique($md5File);
            //file_put_contents('md5list.txt', join($md5File, "\n"));
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    /**
     * 替换图片
     * 百度Web Uploader 插件
     * php服务器
     * */
    public function replace_img(){
        $id = input('id','','intval');
        $res['title'] = '替换';
        $res['base_php'] = url('img/doReplaceImg',array('id'=>$id));
        $this->assign('res',$res);
        return $this->fetch('img/upload');
    }
    // t
    public function doReplaceImg(){
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        $id = intval(input('id'));

        // 查询信息
        $where['id'] = $id;
        $res = $this->model->comGet($id);


        // Support CORS
        // header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }


        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        usleep(5000);

        // Settings
        // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        //$targetDir = 'upload_tmp';
        //$uploadDir = 'uploads/images/';
        //$uploadDir = config('view_replace_str.__UPLOADS__');
        // 获取img_site 的folder字段（站点文件夹）
        $site = $this->imgSiteModel->comGet(session('imgSite'));

        // 上传路径
        $uploadDir = UPLOADS_IMAGES.$site['folder'];
        $targetDir = $uploadDir.'/upload_tmp';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds


        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

        $md5File = @file('md5list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $md5File = $md5File ? $md5File : array();

        if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File ) !== FALSE ) {
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1}');
        }

        /**
         * 图片重新重命名
         * time: 2018-04-04
         * */

        $suffix = explode('.',$fileName);   // 获取文件后缀
        $oldName =  reset($suffix);
        //$fileName = $this->model->imgName().'.'.end($suffix);

        /*命名方式一：201805084235/9c9a086a9fdede7d880ed1a540a5332b.jpg*/
        $p =explode("/",$res['path']);
        $fileName = $p[1];


        /*命名方式二：9c9a086a9fdede7d880ed1a540a5332b.jpg*/
        /*$fileName = $res['path'];*/



        //file_put_contents('1.txt',$this->ImgName());

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;


        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {

                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }



        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);

                        /*图片入库*/
                        $data['id'] = $id;
                        $data['name']  = $res['name'];
                        $data['path'] = $res['path'];
                        $data['add_time'] = time();
                        $this->model->comSave($data,$id);
                        /*图片入库 End*/
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);

            array_push($md5File, md5(file_get_contents($uploadPath)));
            $md5File = array_unique($md5File);
            //file_put_contents('md5list.txt', join($md5File, "\n"));
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    /**
     * 图片列表
     * */
    public function lists(){
        $pid = intval(input('pid'));
        $page = intval(input('page'));

        // 如果传递pid为空，则赋予pid值为默认站点的第一个目录
        if(empty($pid)) $pid = $this->folderModel->defaultFolder();


        $where['pid']=$pid;

        $query['pid'] = $pid;
        $query['page'] = $page;
        $config['query'] = $query;

        $res = $this->model->comPage($this->pagesize,$where,$config,'name+1 asc');//
        // a.图片 格式化数据
        foreach($res['list']['data'] as $k=>$v){
            // 图片地址
            $res['list']['data'][$k]['thumb'] = config('img.domain').$v['path'];
            $res['list']['data'][$k]['name'] = mb_substr($v['name'],0,18,'utf-8');
            $res['list']['data'][$k]['time'] = time();
        }

        // b.文件夹
        $res['folder'] = $this->folderModel->comSelect($where);

        $this->assign('res',$res);
        return $this->fetch();
    }


    /**
     * 图片删除
     * */
    public function ajaxDelImg(){
        isAjaxText();
        $id = intval(input('id'));
        $code = 100;
        $msg = '失败';
        // a.物理删除图片
        $where['id'] = ['in',$id];
        $img = $this->model->comSelect($where,'','path');
        if($img){
            foreach($img as $k=>$v){
                $this->model->unlinkImg($v['path']);
            }
        }

        // b.数据删除
        $res = $this->model->comDestroy($id);
        if($res>0){
            $code = 200;
            $msg = '成功';
        }
        $result['code'] = $code;
        $result['msg'] = $msg;
        return $result;
    }

    /**
     * 批量获取图片路径
     * */
    public function ajaxImgPath(){
        isAjaxText();
        $id = input('id');
        //$id = [145,165];
        $arr = '';
        $res = $this->model->info($id);


        if($res){
            foreach($res as $k=>$v){
                //$arr[] = $this->model->imgHttp($v['path']);
                $arr[] = $v['path'];
            }
        }
        return $arr;
        //print_r($arr);exit;
    }
    // 修改名称
    public function ajaxEditName(){
        isAjaxText();
        $id = intval(input('id'));
        $name = trim(input('name'));
        $data['id'] = $id;
        $data['name'] = $name;
        $res = $this->model->comSave($data,$id);
        return $res;
    }

    /**
     * 图片更换分类
     * @param array $res 返回的是修改过后的数据
     * @return array $json
     * */
    public function doRemovePid(){
        isAjaxText();
        $imgId = intval(input('id'));
        $pid = intval(input('pid'));

        if(empty($pid) || empty($imgId)){
            $code = 100;
            $msg = '分类或者图片ID不能为空';
        }else{
            $arr = explode(',',$imgId);
            foreach($arr as $k=>$v){
                $list[$k]['id'] = $v;
                $list[$k]['pid'] = $pid;
            }
            //print_r($arr);
            $res = $this->model->comSaveAll($list);
            $code =200;
            $msg = '成功';
        }

        $json['code'] = $code;
        $json['msg'] = $msg;
        return $json;

    }






}


